package com.example.anjia03_3z.security;

import com.example.anjia03_3z.mapper.AdminMapper;
import com.example.anjia03_3z.pojo.vo.AdminLoginInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;

/**
 * Spring Security处理认证时使用到的获取管理员登录详情的实现类
 *
 * @author java@tedu.cn
 * @version 0.0.1
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private AdminMapper adminMapper;

    public UserDetailsServiceImpl() {
        log.debug("创建Spring Security的UserDetailsService接口类型的对象：UserDetailsServiceImpl");
    }

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.debug("Spring Security自动调用了loadUserByUsername()方法，参数：{}", s);

        AdminLoginInfoVO loginInfo = adminMapper.getLoginInfoByUsername(s);
        log.debug("根据用户名【{}】查询登录信息，结果：{}", s, loginInfo);
        if (loginInfo == null) {
            String message = "用户名不存在，将无法返回有效的UserDetails对象，则返回null";
            log.warn(message);
            return null;
        }

        log.debug("开始创建返回给Spring Security的UserDetails对象……");
//        UserDetails userDetails = User.builder() // 构建者模式
//                .username(loginInfo.getUsername()) // 存入用户名
//                .password(loginInfo.getPassword()) // 存入密码
//                .disabled(loginInfo.getEnable() != 1) // 存入启用、禁用状态
//                .accountLocked(false) // 存入账号是否锁定的状态
//                .credentialsExpired(false) // 存入凭证是否过期的状态
//                .accountExpired(false) // 存入账号是否过期的状态
//                .authorities("这是一个临时的山寨权限，暂时没什么用") // 存入权限列表
//                .build(); // 执行构建，得到UserDetails类型的对象

        Collection<GrantedAuthority> authorities = new ArrayList<>();
        for (String permission : loginInfo.getPermissions()) {
            authorities.add(new SimpleGrantedAuthority(permission));
        }

        AdminDetails adminDetails = new AdminDetails(
                loginInfo.getId(),
                loginInfo.getUsername(),
                loginInfo.getPassword(),
                loginInfo.getEnable() == 1,
                authorities
        );

        log.debug("即将向Spring Security返回UserDetails类型的对象，返回结果：{}", adminDetails);
        return adminDetails;
    }

}
